//
//  LJFDetailController.m
//  SevenZhou
//
//  Created by qianfeng on 15/9/17.
//  Copyright (c) 2015年 ljf. All rights reserved.
//

#import "LJFDetailController.h"
#import "LJFHttpManager.h"
#import "LJFCustomController.h"
#import "LJFDetailtopView.h"
#import "LJFDetailCollectionCell.h"
#import "LJFIntroduceModel.h"
#import "Helper.h"
#import "LJFDetailModel.h"
#import "LJFCommentsModel.h"
#import "UMSocial.h"
#import "MBProgressHUD.h"

@interface LJFDetailController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,DetailtopViewDelegate,DetailcellDidSelectCellDelegate,UMSocialUIDelegate>
{
    CGPoint _beginTpoint;
    CGPoint _beginCpoint;
    
    UICollectionView *_collectionView;
    
    LJFDetailtopView *_topView;
    
    NSDictionary *_dataDict;
    
    NSArray *_introduceArr;
    NSArray *_commentArr;
    NSArray *_LookArr;
    NSArray *_serviceArr;
    
    int _index;
    
    MBProgressHUD *_HUD;
}

@property (weak, nonatomic) IBOutlet UIImageView *nav_bg;


@end

@implementation LJFDetailController

- (void)initArr
{
    _dataDict = nil;
    _introduceArr = nil;
    _commentArr = nil;
    _LookArr = nil;
    _serviceArr = nil;
}

- (instancetype)initWithCoder:(NSCoder *)coder
{
    self = [super initWithCoder:coder];
    if (self) {
        _index = 1;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self hiddentopbar];
    
    [self hiddenTabar];
    
    [self loadDataFromNetIntroduce];
    
    [self hiddenOrShowTopView];
    
    [self creatCollectionView];
}

- (void)showProgress
{
    _HUD = [[MBProgressHUD alloc] initWithView:self.view];
    _HUD.labelText = @"正在努力加载中";
    
    [self.view addSubview:_HUD];
    
    [_HUD show:YES];
    
}

-(void)createTopViewWithdictionary:(NSDictionary *)dict
{
    _topView = [[NSBundle mainBundle] loadNibNamed:@"LJFDetailtopView" owner:self options:0][0];
    _topView.frame = CGRectMake(0, 20, self.view.frame.size.width, 430);
    [self.view addSubview:_topView];
    _topView.delegate = self;
    _topView.dataDict = dict;
    
    [self.view sendSubviewToBack:_topView];
}



- (void)hiddenOrShowTopView
{
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
    
    [self.view addGestureRecognizer:pan];
}

- (void)hiddentopbar
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 20)];
    view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:view];
}

- (void)pan:(UIPanGestureRecognizer *)pan
{
    
    CGPoint point = [pan translationInView:self.view];
    
    if (pan.state == UIGestureRecognizerStateBegan)
    {
        _beginTpoint = _topView.frame.origin;
        _beginCpoint = _collectionView.frame.origin;
    }
    else if(pan.state == UIGestureRecognizerStateChanged)
    {
        _topView.frame = CGRectMake(0, _beginTpoint.y+point.y, self.view.frame.size.width, 430);
        _collectionView.frame = CGRectMake(0, _beginCpoint.y+point.y, self.view.frame.size.width,self.view.frame.size.height- 64 -50);
        
    }else if (pan.state == UIGestureRecognizerStateEnded)
    {
        if (point.y<-3)
        {
            [UIView animateWithDuration:0.2 animations:^
             {
                 _topView.frame = CGRectMake(0, 50 + 64 - 430, self.view.frame.size.width, 430);
                 _collectionView.frame = CGRectMake(0, 50 + 64, self.view.frame.size.width, self.view.frame.size.height- 64 -50);
                 
                 _nav_bg.alpha = 1.0;
             }];
        }else if(point.y>3)
        {
            [UIView animateWithDuration:0.2 animations:^
             {
                 _topView.frame = CGRectMake(0, 20, self.view.frame.size.width, 430);
                 _collectionView.frame = CGRectMake(0, 450, self.view.frame.size.width, self.view.frame.size.height- 64 -50);
                 
                 _nav_bg.alpha = 0;
             }];

        }
    }

}

- (void)hiddenTabar
{
    LJFCustomController *tabar = (LJFCustomController *)self.tabBarController;
    
    tabar.tabBarView.hidden = YES;
}

- (void)showTabar
{
    LJFCustomController *tabar = (LJFCustomController *)self.tabBarController;
    
    tabar.tabBarView.hidden = NO;
}

- (void)loadDataFromNetIntroduce
{
    [self showProgress];
    
    [[LJFHttpManager shareInstance] getDataFromNetWithUrl:URL_introduce AndParameterStr:URL_detail_parameter andIdString:_goodsid andPage:0 success:^(id responseObj)
    {
        NSDictionary *dict = responseObj[@"data"];
        
        _dataDict = [NSDictionary dictionaryWithDictionary:dict];
        
        [self createTopViewWithdictionary:dict];
        
        [_collectionView reloadData];
        
        [_HUD hide:YES];
        
    } failure:^(NSError *error)
    {
       NSLog(@"error == %@",error);
    }];
}


- (void)loadDataFromNetDetail
{
    if (_introduceArr.count != 0)
    {
        return;
    }
    
    [self showProgress];
    
    [[LJFHttpManager shareInstance] getDataFromNetWithUrl:URL_detail AndParameterStr:URL_detail_parameter andIdString:_goodsid andPage:0 success:^(id responseObj)
     {
         NSArray *array = responseObj[@"data"];
         
         NSMutableArray *arrM = [NSMutableArray array];
         
         CGFloat width = self.view.frame.size.width - 100 - 10;
         
         for (NSDictionary *dic in array)
         {
             LJFIntroduceModel *model = [[LJFIntroduceModel alloc] init];
             
             model.title = dic[@"title"];
             
             NSMutableArray *arrM1 = [NSMutableArray array];
             
             for (NSDictionary *dict in dic[@"detail_value"])
             {
                 NSString *value = dict[@"value"];
                 
                 CGFloat heigth = [Helper heightOfString:value font:[UIFont systemFontOfSize:15] width:width] + 10;
                 
                 LJFDetailModel *model = [[LJFDetailModel alloc] init];
                 
                 model.name = dict[@"ti_title"];
                 model.value = dict[@"value"];
                 model.heigth = [NSString stringWithFormat:@"%f",heigth];
                 
                 [arrM1 addObject:model];
                 
             }
             
             model.childArr = [NSArray arrayWithArray:arrM1];
             
             [arrM addObject:model];
         }
         
         _introduceArr = [NSArray arrayWithArray:arrM];
         
         [_collectionView reloadData];
         
         [_HUD hide:YES];
         
     } failure:^(NSError *error)
     {
         NSLog(@"error == %@",error);
     }];
}

- (void)loadDataFromNetComments
{
    if (_commentArr.count != 0)
    {
        return;
    }
    
    [self showProgress];
    
    [[LJFHttpManager shareInstance] getDataFromNetWithUrl:URL_comments AndParameterStr:URL_comments_parameter andIdString:_goodsid andPage:_index success:^(id responseObj)
     {
         NSMutableArray *arrM = [[NSMutableArray alloc] init];
         
         for (NSDictionary *dict in responseObj[@"data"])
         {
             LJFCommentsModel *model = [[LJFCommentsModel alloc] initWithDictionary:dict];
             
             [arrM addObject:model];
         }
         
         _commentArr = [NSArray arrayWithArray:arrM];
         
         
         [_collectionView reloadData];
         
         [_HUD hide:YES];
         
     } failure:^(NSError *error)
     {
         NSLog(@"error == %@",error);
     }];
}

- (void)loadDataFromNetLook
{
    if (_LookArr.count != 0)
    {
        return;
    }
    
    [self showProgress];
    
    [[LJFHttpManager shareInstance] getDataFromNetWithUrl:URL_take_a_look AndParameterStr:URL_detail_parameter andIdString:_goodsid andPage:0 success:^(id responseObj)
     {
         NSMutableArray *arrM = [[NSMutableArray alloc] init];
         
         NSDictionary *dict = responseObj[@"data"];
         
         NSDictionary *exp_detail = dict[@"exp_detail"];
         
         LJFIntroduceModel *model = [[LJFIntroduceModel alloc] init];
         model.title = exp_detail[@"title"];
         
         LJFDetailModel *Dmodel = [[LJFDetailModel alloc] init];
         Dmodel.value = exp_detail[@"detail_value"];
         Dmodel.name = exp_detail[@"image"];
         CGFloat heigth = [Helper heightOfString:exp_detail[@"detail_value"] font:[UIFont systemFontOfSize:15] width:self.view.frame.size.width-30] + 10 + 170;
         Dmodel.heigth = [NSString stringWithFormat:@"%f",heigth];
         
         NSArray *arr = @[Dmodel];
         model.childArr = [NSArray arrayWithArray:arr];
         
         [arrM addObject:model];
         
         
         NSDictionary *detail_img = dict[@"detail_img"];
         
         LJFIntroduceModel *model1 = [[LJFIntroduceModel alloc] init];
         model1.title = detail_img[@"title"];
         
         NSMutableArray *arr1 = [[NSMutableArray alloc] init];
         for (NSDictionary *dic in detail_img[@"goods_detail_img"])
         {
             LJFDetailModel *Imodel = [[LJFDetailModel alloc] init];
             
             Imodel.name = dic[@"img_url"];
             Imodel.value = dic[@"img_desc"];
             Imodel.myid = dic[@"img_id"];
             
             CGFloat heigth = [Helper heightOfString:dic[@"img_desc"] font:[UIFont systemFontOfSize:15] width:self.view.frame.size.width-30] + 10 + 170;
             Imodel.heigth = [NSString stringWithFormat:@"%f",heigth];
             
             [arr1 addObject:Imodel];
         }
         model1.childArr = [NSArray arrayWithArray:arr1];
         
         [arrM addObject:model1];
         
         _LookArr = [NSArray arrayWithArray:arrM];
         
         [_collectionView reloadData];
         
         [_HUD hide:YES];
         
     } failure:^(NSError *error)
     {
         NSLog(@"error == %@",error);
     }];
}

- (void)loadDataFromNetService
{
    if (_serviceArr.count != 0)
    {
        return;
    }
    
    [self showProgress];
    
    [[LJFHttpManager shareInstance] getDataFromNetWithUrl:URL_service_relevant AndParameterStr:URL_detail_parameter andIdString:_goodsid andPage:0 success:^(id responseObj)
     {
         NSDictionary *dict = responseObj[@"data"];
         
         NSArray *arr = [NSArray arrayWithArray:dict[@"bought_goods"]];
         NSArray *arr1 = [NSArray arrayWithArray:dict[@"linked_goods"]];
         
         _serviceArr = [NSArray arrayWithObjects:arr,arr1, nil];
         
         
         [_collectionView reloadData];
         
         [_HUD hide:YES];
         
     } failure:^(NSError *error)
     {
         NSLog(@"error == %@",error);
     }];
}



- (IBAction)back:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
    
    [self showTabar];
}

- (void)creatCollectionView
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.minimumInteritemSpacing = 0;
    layout.minimumLineSpacing = 0;
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    layout.itemSize = CGSizeMake(self.view.frame.size.width, self.view.frame.size.height- 64 -50);
    
    _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 450, self.view.frame.size.width, self.view.frame.size.height- 64 -50)collectionViewLayout:layout];
    _collectionView.dataSource =self;
    _collectionView.delegate =self;
    _collectionView.pagingEnabled =YES;
    _collectionView.backgroundColor = [UIColor clearColor];
    
    [self.view addSubview:_collectionView];
    
    [_collectionView registerNib:[UINib nibWithNibName:@"LJFDetailCollectionCell" bundle:nil] forCellWithReuseIdentifier:@"LJFDetailCollectionCell"];

}

- (void)loadDataWithIndex:(NSInteger) index
{
    switch (index)
    {
        case 1:
        {
            [self loadDataFromNetDetail];
        }
            break;
        case 2:
        {
            [self loadDataFromNetComments];
        }
            break;
        case 3:
        {
            [self loadDataFromNetLook];
        }
            break;
        case 4:
        {
            [self loadDataFromNetService];
        }
            break;
            
        default:
            break;
    }
    
}

#pragma mark -DetailtopViewDelegate

- (void)DetailtopViewOffsetCollection:(LJFDetailtopView *)topview andoffset:(NSInteger)index
{
    [_collectionView setContentOffset:CGPointMake(self.view.frame.size.width*index, 0) animated:YES];
    //[_collectionView reloadData];
    
    [self loadDataWithIndex:index];
}


- (IBAction)shar:(UIButton *)sender
{
   // NSLog(@"dict == %@",_dataDict);
    
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:_dataDict[@"img"][@"thumb"]]];
    UIImage *image = [UIImage imageWithData:data];
    
    NSString *text = _dataDict[@"goods_name"];
    
    [UMSocialSnsService
     presentSnsIconSheetView:self
     appKey:nil
     shareText:text
     shareImage:image
     shareToSnsNames:@[UMShareToSina,UMShareToTencent,UMShareToRenren,UMShareToDouban,UMShareToWechatSession,UMShareToWechatTimeline,UMShareToWechatFavorite]
     delegate:self];

}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark -UICollectionViewDataSource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 5;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{

    LJFDetailCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"LJFDetailCollectionCell" forIndexPath:indexPath];
    cell.mydelegate = self;
    
    cell.dataDict = _dataDict;
    cell.introduceArr = _introduceArr;
    cell.commentArr = _commentArr;
    cell.LookArr = _LookArr;
    cell.serviceArr = _serviceArr;
    
    cell.collectionRow = indexPath.row;

    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(self.view.frame.size.width, self.view.frame.size.height- 64 -50);
}

#pragma mark -scrollView

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    NSInteger index = _collectionView.contentOffset.x/_collectionView.frame.size.width;
    
    [self loadDataWithIndex:index];

}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat index = _collectionView.contentOffset.x/_collectionView.frame.size.width;
    
    _topView.greenX.constant = index*(self.view.frame.size.width/5.0);
}

#pragma mark -DetailcellDidSelectCellDelegate

- (void)Detailcell:(LJFDetailCollectionCell *)cell DidSelectedIndex:(NSIndexPath *)indexPath
{
    NSArray *arr = _serviceArr[indexPath.section];
    NSDictionary *dict = arr[indexPath.row];
    
    LJFDetailController *detail = [self.storyboard instantiateViewControllerWithIdentifier:@"LJFDetailController"];
    detail.goodsid = dict[@"goods_id"];
    
    [self.navigationController pushViewController:detail animated:YES];
}



@end
